package reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class FieldDemo {


    @Test
    public void test2() throws Exception {
//        getDeclaredFields: 获取所有的属性
//        getDeclaredField 获取单个成员，参数传入属性名
//
        Class c = Class.forName("reflect.Person");
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("---------------");
        Field f = c.getDeclaredField("name");
        f.setAccessible(true);

        Person person = (Person) c.getConstructor().newInstance();
        f.set(person, "小明");
        System.out.println(person);
    }

    @Test
    public void test1() throws Exception {
        Class c = Class.forName("reflect.Person");

        // getFields: 获取public修饰的属性
        Field[] fields = c.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        // 参数是属性名
        Field f1 = c.getField("height");
        System.out.println(f1);

        // 使用 Field 对象
        // 设置属性值, 需要现有对象
        Person person = (Person) c.getConstructor().newInstance();
        f1.set(person, 170);
        System.out.println(person);


    }
}
